﻿/*********************************************************

    Copyright (c) Microsoft. All rights reserved.
    This code is licensed under the Microsoft Public License.
    THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
    ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
    IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
    PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.

*********************************************************/
using System;
using System.Windows;
using System.Windows.Controls;
using OData.Silverlight;
using System.Windows.Media.Imaging;

namespace SL_OData_Explorer
{
    public class ODataMediaColumn : DataGridBoundColumn
    {

        protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem)
        {
            throw new NotImplementedException();
        }

        protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem)
        {
            ODataEntity entity = dataItem as ODataEntity;
            switch (EDMUtility.GetMediaType(entity.MediaType))
            {
                case MediaType.Image:
                    Image imageColumn = new Image();
                    if (!String.IsNullOrEmpty(entity.MediaUri))
                    {
                        Uri mediaLinkUri = new Uri(entity.MediaUri, UriKind.RelativeOrAbsolute);
                        if (!mediaLinkUri.IsAbsoluteUri)
                        {
                            mediaLinkUri = new Uri(
                                    String.Format("{0}/{1}", App.MDViewModel.CurrentModel.ServiceDocument.BaseUri.OriginalString.TrimEnd('/'), mediaLinkUri.OriginalString.TrimStart('/')),
                                    UriKind.Absolute);
                        }
                        BitmapImage bitmap = new BitmapImage(mediaLinkUri);
                        imageColumn.Source = bitmap;
                    }
                    return imageColumn;
                case MediaType.Document:
                    HyperlinkButton downloadButton = new HyperlinkButton();
                    downloadButton.Content = "Download ";
                    downloadButton.NavigateUri = new Uri(entity.MediaUri);
                    return downloadButton;
                default:
                    TextBlock textBlock = new TextBlock() { Text = "No Media Found" };
                    return textBlock;
            }

        }

        protected override object PrepareCellForEdit(FrameworkElement editingElement, RoutedEventArgs editingEventArgs)
        {
            throw new NotImplementedException();
        }
    }
}
